﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace WpfPaintIntersect
{
    public static class ClippingEar
    {
        
        /// <summary>
        /// Lines the intersect.
        /// http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry2
        /// </summary>
        /// <param name="x1">The x1.</param>
        /// <param name="x2">The x2.</param>
        /// <param name="y1">The y1.</param>
        /// <param name="y2">The y2.</param>
        /// <returns></returns>
        public static bool LineIntersect(Point x1, Point x2, Point y1, Point y2, out Point intersect)
        {
            intersect = new Point();;
            // prvni usecka
            double a1 = x2.Y - x1.Y;
            double b1 = x1.X - x2.X;
            double c1 = a1 * x1.X + b1 * x1.Y;

            // druha usecka
            double a2 = y2.Y - y1.Y;
            double b2 = y1.X - y2.X;
            double c2 = a2 * y1.X + b2 * y1.Y;

            double det = a1 * b2 - a2 * b1;

            // nejsou rovnobezky
            if (det != 0)
            {
                double x = (b2 * c1 - b1 * c2) / det;
                double y = (a1 * c2 - a2 * c1) / det;
                
                // pokud je prusecik mezi body, tak true
                if (Math.Min(x1.X, x2.X) <= x && x <= Math.Max(x1.X, x2.X)
                    && Math.Min(y1.Y, y2.Y) <= y && y <= Math.Max(y1.Y, y2.Y))
                {
                    intersect.X = x;
                    intersect.Y = y;

                    return true;
                }
            }

            return false;
        }
    }
    
}
